package com.zc.mall.service.impl;

import com.zc.mall.dao.UserMapper;
import com.zc.mall.pojo.User;
import com.zc.mall.service.IUserService;
import com.zc.mall.vo.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

import static com.zc.mall.enums.ResponseEnum.*;
import static com.zc.mall.enums.RoleEnum.CUSTOMER;

/**
 * @author 曾川
 * @version 1.0.0
 * @ClassName IUserServiceImpl.java
 * @Description 用户实现类
 * @createTime 2021年06月01日 16:35:00
 */
@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ResponseVo<User> register(User user) {
        //判断username、email是否重复
        int countByUsername = userMapper.countByUsername(user.getUsername());
        if (countByUsername > 0) {
            return ResponseVo.error(USERNMAE_EXIST);
        }
        int countByEmail = userMapper.countByEmail(user.getEmail());
        if (countByEmail > 0) {
            return ResponseVo.error(PASSWORD_EXIST);
        }
        //默认为顾客
        user.setRole(CUSTOMER.getCode());
        //MD5加密密码  DigestUtils.md5DigestAsHex 是Spring自带的
        user.setPassword(DigestUtils.md5DigestAsHex(
                user.getPassword().getBytes(StandardCharsets.UTF_8)));
        //写入数据库
        int resultCount = userMapper.insertSelective(user);

        if (resultCount == 0 ) {
           return ResponseVo.error(ERROR);
        }

        return ResponseVo.success();

    }

    /**
     * 登录
     *
     * @param username
     * @param password
     */
    @Override
    public ResponseVo<User> login(String username,String password) {
        //查询用户
        User user = userMapper.selectByUsername(username);
        //判断用户是否存在
        if (user == null){
            return ResponseVo.error(USERNAME_OR_PASSWORD_ERROR);
        }
        //判断密码是否正确（忽略大小写）
        if (!(user.getPassword().equalsIgnoreCase(
                DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8))))){
            return ResponseVo.error(USERNAME_OR_PASSWORD_ERROR);
        }

        //返回对象给前端时  不要传password
        user.setPassword("");
        return ResponseVo.success(user);
    }


}
